
import { Tag, Col } from 'antd';
import React from 'react';
const { CheckableTag } = Tag;

interface IProps {
    onFilter: (selectedSizes: string[]) => void;
    sizes: string[];
    selectedSizes?: string[];
    multiple?: boolean;
    colProps: any;
}
interface IState {
    sizesMap: { [size: string]: boolean };
}
export class ProductSizes extends React.Component<IProps, IState> {
    constructor(props: IProps) {
        super(props);
        const sizeMap: { [size: string]: boolean } = {};
        props.selectedSizes?.forEach(s => sizeMap[s] = true);
        this.state = {
            sizesMap: sizeMap,
        };
    }

    componentDidUpdate(prevProps: Readonly<IProps>, _: Readonly<IState>, snapshot?: any): void {
        if (prevProps.selectedSizes === this.props.selectedSizes) return;
        const sizeMap: { [size: string]: boolean } = {};
        this.props.selectedSizes?.forEach(s => sizeMap[s] = true);
        this.setState({
            sizesMap: sizeMap,
        });
    }

    onChange = (size: string, checked: boolean) => {

        if (this.props.multiple) {
            const newSizeMap = { ...this.state.sizesMap, [size]: checked };
            this.setState({
                sizesMap: newSizeMap,
            });
            const selectedSizes = Object.keys(newSizeMap).filter(s => newSizeMap[s]);
            this.props.onFilter(selectedSizes);
        } else {
            this.setState({
                sizesMap: { [size]: checked },
            });
            this.props.onFilter(checked ? [size] : []);
        }
    };

    render() {
        return (
            <>
                {this.props.sizes.map(size => (
                    <Col key={size} {...this.props.colProps} style={{ textAlign: 'center' }}>
                        <CheckableTag
                            className='checkProductSize'
                            checked={this.state.sizesMap[size]}
                            onChange={checked => this.onChange(size, checked)}
                        >
                            {size}
                        </CheckableTag>
                    </Col>
                ))}
            </>
        );
    }
}

export default ProductSizes;
